const express = require('express');
const User = require('../models/user');
const jwt = require('jsonwebtoken');
const config = require('../config');
const passport = require('passport');
const router = express.Router();

require('../passport')(passport);

// 注册账户
router.post('/user', (req, res) => {
  if (!req.body.name || !req.body.password) {
    res.status(400).json({ success: false, message: '请输入用户名或密码' });
  } else {
    User.create({
      name: req.body.name,
      password: req.body.password,
      email: req.body.email,
      createAt: new Date(),
      updateAt: new Date(),
      loginIp: req.ip
    }).then(() => {
      res.json({ success: true, message: '创建新用户成功' });
    })
      .catch(err => {
        res.status(500).json({ success: false, message: '注册失败，请稍后重试!', info: err });
      });
  }
});

// 检测用户名与密码并成功一个accesstoken
router.post('/user/token', (req, res) => {
  User.findOne({
    name: req.body.name
  }, (err, user) => {
    if (err) {
      throw err;
    }
    if (!user) {
      res.status(401).json({ success: false, message: '认证失败，用户不存在' });
    } else if (user) {
      user.comparePassword(req.body.password, (err, isMatch) => {
        if (isMatch && !err) {
          let token = jwt.sign({ name: user.name }, config.secret, {
            expiresIn: 10080
          });
          user.token = token;
          user.save((err) => {
            if (err) {
              throw err;
            }
          });
          res.json({
            success: true,
            message: '验证成功',
            token: 'Bearer ' + token,
            name: user.name
          });
        } else {
          res.status(401).json({ success: false, message: '认证失败，账号或密码错误' });
        }
      });
    }
  });
});

// passport-http-bearer token 中间件验证
// 通过header发送Authorization -> Bearer + token
router.get('/user', passport.authenticate('bearer', { session: false }), (req, res) => {
  let fullToken = 'Bearer ' + req.user.token;
  req.user['token'] = fullToken;
  res.json({ success: true, message: '查询成功', data: req.user });
});

module.exports = router;
